﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using Sirenix.OdinInspector;

namespace Miao.UI
{
    /// <summary>
    /// 另一种打字机功能的测试
    /// 
    /// </summary>
    public class TyperDialog : UIMotionPanel
    {
        [Title("打字机组件")]
        public TyperDialogTextMeshPro typerDialog;
        
        [Title("播放设置")]
        [Tooltip("自动播放")]
        public bool autoPlay = true;
        
        [Tooltip("自动播放间隔时间（秒）")]
        public float autoPlayInterval = 2f;
        
        [Tooltip("需要播放的文本")]
        public string[] textLines;
        
        [Tooltip("播放完成后是否隐藏面板")]
        public bool hideOnComplete = true;
        
        [Title("UI组件")]
        [Tooltip("下一句按钮")]
        public Button nextButton;
        
        [Title("播放速度设置")]
        [Tooltip("播放速度（每秒进度 0-1）")]
        [Range(0.1f, 2.0f)]
        public float playSpeed = 0.5f;
        
        /// <summary>
        /// 当前播放的文本索引
        /// </summary>
        public int currentTextIndex { get; private set; }
        
        /// <summary>
        /// 是否正在播放
        /// </summary>
        public bool isPlaying { get; private set; }
        
        /// <summary>
        /// 播放完成事件
        /// </summary>
        public event Action OnPlayCompleted;
        
        /// <summary>
        /// 单行文本播放完成事件
        /// </summary>
        public event Action<int> OnLineCompleted;
        
        /// <summary>
        /// 延迟调用句柄
        /// </summary>
        private DelayCallHandle delayCallHandle;
        
        /// <summary>
        /// 当前播放进度（0-1）
        /// </summary>
        private double currentProgress = 0;
        
        /// <summary>
        /// 当前行是否播放完成
        /// </summary>
        private bool isCurrentLineCompleted = false;
        
        /// <summary>
        /// 等待下一行的计时器
        /// </summary>
        private float waitTimer = 0f;
        
        /// <summary>
        /// 是否正在等待下一行
        /// </summary>
        private bool isWaitingForNext = false;
        
        public override async Task OnCreate()
        {
            await base.OnCreate();
            
            if (nextButton != null)
            {
                nextButton.onClick.AddListener(OnNextButtonClick);
            }
        }
        
        public override void OnClose()
        {
            base.OnClose();
            
            if (nextButton != null)
            {
                nextButton.onClick.RemoveListener(OnNextButtonClick);
            }
            
            // 清理延迟调用
            delayCallHandle?.Kill();
        }
        
        private void Update()
        {
            if (!isPlaying) return;
            
            if (isWaitingForNext)
            {
                // 等待下一行的逻辑
                waitTimer -= Time.deltaTime;
                if (waitTimer <= 0)
                {
                    isWaitingForNext = false;
                    PlayNextLine();
                }
                return;
            }
            
            // 更新当前行的播放进度
            if (!isCurrentLineCompleted)
            {
                currentProgress += playSpeed * Time.deltaTime;
                
                if (currentProgress >= 1.0)
                {
                    currentProgress = 1.0;
                    isCurrentLineCompleted = true;
                    OnLineCompleted?.Invoke(currentTextIndex);
                    
                    if (autoPlay)
                    {
                        // 开始等待下一行
                        isWaitingForNext = true;
                        waitTimer = autoPlayInterval;
                    }
                }
                
                // 更新打字机显示
                typerDialog.RefreshShow(currentProgress);
            }
        }
        
        /// <summary>
        /// 开始播放文本
        /// </summary>
        public void Play()
        {
            currentTextIndex = 0;
            isPlaying = true;
            isCurrentLineCompleted = false;
            isWaitingForNext = false;
            PlayCurrentLine();
        }
        
        /// <summary>
        /// 异步播放文本
        /// </summary>
        public async Task PlayAsync()
        {
            var tcs = new TaskCompletionSource<bool>();
            
            Action tempHandler = null;
            tempHandler = () =>
            {
                OnPlayCompleted -= tempHandler;
                tcs.SetResult(true);
            };
            OnPlayCompleted += tempHandler;
            
            Play();
            await tcs.Task;
        }
        
        /// <summary>
        /// 播放当前行文本
        /// </summary>
        private void PlayCurrentLine()
        {
            if (currentTextIndex >= textLines.Length)
            {
                // 播放完成
                isPlaying = false;
                OnPlayCompleted?.Invoke();
                
                if (hideOnComplete)
                {
                    delayCallHandle = MiaoRuntime.Updater.AddDelayCall(Hide, autoPlayInterval);
                }
                return;
            }
            
            // 设置文本并开始播放
            typerDialog.SetText(textLines[currentTextIndex]);
            typerDialog.ClearAllAlpha();
            currentProgress = 0;
            isCurrentLineCompleted = false;
            isWaitingForNext = false;
        }
        
        /// <summary>
        /// 播放下一行
        /// </summary>
        private void PlayNextLine()
        {
            currentTextIndex++;
            PlayCurrentLine();
        }
        
        /// <summary>
        /// 下一句按钮点击事件
        /// </summary>
        private void OnNextButtonClick()
        {
            // 如果正在播放当前行，立即完成
            if (isPlaying && !isCurrentLineCompleted)
            {
                CompleteCurrentLine();
                currentTextIndex++;
                
                if (autoPlay)
                {
                    isWaitingForNext = true;
                    waitTimer = autoPlayInterval;
                }
                else
                {
                    PlayCurrentLine();
                }
            }
            else if (isWaitingForNext)
            {
                // 如果正在等待，立即播放下一行
                isWaitingForNext = false;
                PlayNextLine();
            }
            else
            {
                // 直接播放下一句
                PlayNextLine();
            }
        }
        
        /// <summary>
        /// 立即完成当前播放
        /// </summary>
        public void CompleteCurrentLine()
        {
            currentProgress = 1.0;
            isCurrentLineCompleted = true;
            typerDialog.RefreshShow(currentProgress);
        }
        
        /// <summary>
        /// 停止播放
        /// </summary>
        public void Stop()
        {
            isPlaying = false;
            isCurrentLineCompleted = false;
            isWaitingForNext = false;
            delayCallHandle?.Kill();
        }
        
        /// <summary>
        /// 设置播放速度
        /// </summary>
        /// <param name="speed">每秒进度（0-1）</param>
        public void SetPlaySpeed(float speed)
        {
            playSpeed = Mathf.Clamp(speed, 0.1f, 2.0f);
        }
        
        /// <summary>
        /// 设置自动播放间隔
        /// </summary>
        /// <param name="interval">间隔时间（秒）</param>
        public void SetAutoPlayInterval(float interval)
        {
            autoPlayInterval = Mathf.Max(0, interval);
        }
        
        /// <summary>
        /// 获取当前播放进度
        /// </summary>
        /// <returns>当前行播放进度（0-1）</returns>
        public double GetCurrentProgress()
        {
            return currentProgress;
        }
        
        /// <summary>
        /// 获取总播放进度
        /// </summary>
        /// <returns>总播放进度（0-1）</returns>
        public double GetTotalProgress()
        {
            if (textLines == null || textLines.Length == 0)
                return 0;
                
            return (double)currentTextIndex / textLines.Length;
        }
    }
}
